//
//  WYHttpServer.m
//  JinMiTong
//
//  Created by 曹运 on 2017/3/14.
//  Copyright © 2017年 com.liji. All rights reserved.
//

#import "WYHttpServer.h"
#import "AFNetworkActivityIndicatorManager.h"
#import "FYError.h"
#import "WYLoginController.h"
@implementation WYHttpServer
static WYHttpServer *_shareInstance=nil;
+ (WYHttpServer *) sharedInstance
{
    if(!_shareInstance)
    {
        _shareInstance=[[WYHttpServer alloc] init];
    }
    return _shareInstance;
}
- (AFHTTPSessionManager *)requestManager
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 30.0;
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    
//    NSString *cookiesdata = [[NSUserDefaults standardUserDefaults] valueForKey:@"wyuser"]?[[NSUserDefaults standardUserDefaults] valueForKey:@"wyuser"]:@"";
//    if (cookiesdata.length>0) {
//        [manager.requestSerializer setValue:cookiesdata forHTTPHeaderField:@"Cookie"];
//    }
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/plain"];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"multipart/form-data"];
    
    
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.validatesDomainName = NO;
    manager.securityPolicy = securityPolicy;
//    [manager setSecurityPolicy:[self customSecurityPolicy]];
//    NSArray * cookies = [NSKeyedUnarchiver unarchiveObjectWithData: [[NSUserDefaults standardUserDefaults] objectForKey:kCookie]];
//    NSHTTPCookieStorage * cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//    for (NSHTTPCookie * cookie in cookies){
//        [cookieStorage setCookie: cookie];
//    }
    return manager;
}
-(AFSecurityPolicy *)customSecurityPolicy {
    
    // 先导入证书 证书由服务端生成，具体由服务端人员操作
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"cer"];//证书的路径
    NSData *cerData = [NSData dataWithContentsOfFile:cerPath];
    
    // AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    //validatesDomainName 是否需要验证域名，默认为YES;
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = NO;
    
    securityPolicy.pinnedCertificates = [[NSSet alloc] initWithObjects:cerData,nil];
    
    return securityPolicy;
}

- (NSMutableDictionary *)requestParameters
{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    NSString *token =[WYStoreModule currentToken];
   // [parameters setValue:@"IOS" forKey:@"DeviceType"];
    if (token.length) {
          [parameters setValue:token forKey:@"token"];
    }
    
  
//    NSString *token = [WYStoreModule currentToken];
//    if (token.length > 0) {
//        [parameters setValue:token forKey:@"token"];
//    }
    return parameters;
}
- (NSURLSessionDataTask *)postOperationWithManger:(AFHTTPSessionManager *)manager Url:(NSString *)urlString WithPara:(NSDictionary *)para Success:(void(^)(BOOL success,id response,NSString *errorMsg)) complete
{
    NSLog(@"请求参数：%@", para);
    NSLog(@"请求地址：%@",urlString);
    NSURLSessionDataTask *dataTask = [manager POST:urlString parameters:para progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"%lld", uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:NULL];
  //      NSDictionary *dic = [WYHttpServer responseConfiguration:responseObject];
        if (![dic isKindOfClass:[NSDictionary class]]) {
            HUDNormal(@"服务器闹点小情绪,努力安抚中,请稍候~");
            [[NSNotificationCenter defaultCenter] postNotificationName:@"hiddenLoading" object:nil];
            return;
        }
        NSLog(@"response===%@",dic);
        if ([dic[@"code"] integerValue]==0) {
            complete(YES,dic,nil);
        }else if([dic[@"code"] integerValue]==1001||[dic[@"code"] integerValue]==1003) {
            [[FYAlertTooler sharedInstance] showAlertTitle:@"" message:@"登录超时，请重新登录" btnTitles:@"确定" btnClicked:^(NSInteger index) {
                
                
                
                
                
                AppDelegate *appdelegate = APPDELEGATE;
                WYLoginController *loginVc = [[WYLoginController alloc] initWithNibName:@"WYLoginController" bundle:nil];
                UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginVc];
                 [WYStoreModule cleanToken];
                
                [appdelegate.window.rootViewController presentViewController:nav animated:YES completion:nil];
            }];
            
            
           // complete(NO,dic,dic[@"msg"]);
        }else {
            complete(NO,dic,dic[@"msg"]);
            
            
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"hiddenLoading" object:nil];
//            [[FYAlertTooler sharedInstance] showAlertTitle:@"" message:@"登录超时，请重新登录" btnTitles:@"确定" btnClicked:^(NSInteger index) {
//                AppDelegate *appdelegate = APPDELEGATE;
//                [appdelegate.rootNav popToRootViewControllerAnimated:NO];
//                WYLoginController *loginVc = [[WYLoginController alloc] initWithNibName:@"WYLoginController" bundle:nil];
//                NSDictionary *userMsg = [[NSUserDefaults standardUserDefaults] objectForKey:kLoginMsg];
//                if (userMsg) {
//                    loginVc.userNameStr = userMsg[@"userName"];
//                }
//                [[NSUserDefaults standardUserDefaults] removeObjectForKey:kCookie];
//                [WYStoreModule removeUserMessage];
//                [appdelegate.rootNav presentViewController:loginVc animated:YES completion:nil];
//            }];
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        FYError *rError = [FYError errorWithOperation:task];
        complete(NO,nil,rError.errorMessage);
    }];
    return dataTask;
}
- (NSURLSessionDataTask *)getOperationWithManger:(AFHTTPSessionManager *)manager Url:(NSString *)urlString WithPara:(NSDictionary *)para Success:(void(^)(BOOL success,id response,NSString *errorMsg)) complete
{
    NSLog(@"请求参数：%@", para);
    NSLog(@"请求地址：%@",urlString);
    NSURLSessionDataTask *dataTask = [manager GET:urlString parameters:para progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"%lld", uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:NULL];
        if (![dic isKindOfClass:[NSDictionary class]]) {
            HUDNormal(@"服务器闹点小情绪,努力安抚中,请稍候~");
            [[NSNotificationCenter defaultCenter] postNotificationName:@"hiddenLoading" object:nil];
            return;
        }
        if ([dic[@"code"] integerValue]==0) {
            complete(YES,dic,nil);
        }else if([dic[@"code"] integerValue]==1001) {
            
        [[FYAlertTooler sharedInstance] showAlertTitle:@"" message:@"登录超时，请重新登录" btnTitles:@"确定" btnClicked:^(NSInteger index) {
           AppDelegate *appdelegate = APPDELEGATE;
           WYLoginController *loginVc = [[WYLoginController alloc] initWithNibName:@"WYLoginController" bundle:nil];
        [appdelegate.window.rootViewController presentViewController:loginVc animated:YES completion:nil];
        }];
        }else {
            complete(NO,dic,dic[@"err_msg"]);
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"hiddenLoading" object:nil];
//            [[FYAlertTooler sharedInstance] showAlertTitle:@"" message:@"登录超时，请重新登录" btnTitles:@"确定" btnClicked:^(NSInteger index) {
//              //  AppDelegate *appdelegate = APPDELEGATE;
////                [appdelegate.rootNav popToRootViewControllerAnimated:NO];
////                WYLoginController *loginVc = [[WYLoginController alloc] initWithNibName:@"WYLoginController" bundle:nil];
////                [[NSUserDefaults standardUserDefaults] removeObjectForKey:kCookie];
////                [WYStoreModule removeUserMessage];
////                [appdelegate.rootNav presentViewController:loginVc animated:YES completion:nil];
//            }];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        FYError *rError = [FYError errorWithOperation:task];
        complete(NO,nil,rError.errorMessage);
    }];
    return dataTask;
}
+(id)responseConfiguration:(id)responseObject{
    
    NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    return dic;
}
@end
